<template>
  <div class="reader-page">
    <div class="reader-header">
      <div class="reader-controls">
        <button @click="goBack" class="btn">← 返回</button>
        <div class="book-info">
          <h1 class="book-title">{{ book?.title || '加载中...' }}</h1>
          <span class="book-author">{{ book?.author || '' }}</span>
        </div>
        <div class="reader-actions">
          <button @click="downloadBook" class="btn">下载文件</button>
          <button @click="toggleFullscreen" class="btn">全屏</button>
        </div>
      </div>
    </div>
    
    <div class="reader-container" ref="readerContainer">
      <div v-if="loading" class="loading">
        <p>正在加载书籍...</p>
      </div>
      
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="loadBook" class="btn">重试</button>
      </div>
      
      <div v-else class="reader-content">
        <!-- PDF阅读器 -->
        <div v-if="book?.fileType === 'PDF'" class="pdf-reader">
          <div class="reader-notice">
            <p>📖 当前为MVP版本，PDF阅读器功能有限</p>
            <p>请使用下载按钮获取完整文件</p>
          </div>
          <canvas ref="pdfCanvas" class="pdf-canvas"></canvas>
          <div class="pdf-controls">
            <button @click="prevPage" :disabled="currentPage <= 1" class="btn">上一页</button>
            <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
            <button @click="nextPage" :disabled="currentPage >= totalPages" class="btn">下一页</button>
          </div>
        </div>
        
        <!-- EPUB阅读器 -->
        <div v-else-if="book?.fileType === 'EPUB'" class="epub-reader">
          <div class="reader-notice">
            <p>📚 当前为MVP版本，EPUB阅读器功能有限</p>
            <p>请使用下载按钮获取完整文件</p>
          </div>
          <div ref="epubContainer" class="epub-container"></div>
          <div class="epub-controls">
            <button @click="prevChapter" class="btn">上一章</button>
            <span class="chapter-info">{{ currentChapter }} / {{ totalChapters }}</span>
            <button @click="nextChapter" class="btn">下一章</button>
          </div>
        </div>
        
        <!-- TXT阅读器 -->
        <div v-else-if="book?.fileType === 'TXT'" class="txt-reader">
          <div class="txt-content">
            <pre>{{ textContent }}</pre>
          </div>
        </div>
        
        <div v-else class="unsupported">
          <p>不支持的文件格式: {{ book?.fileType }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBookStore } from '@/stores/book'

const route = useRoute()
const router = useRouter()
const bookStore = useBookStore()

const book = ref(null)
const loading = ref(true)
const error = ref('')

// PDF相关
const pdfCanvas = ref(null)
const currentPage = ref(1)
const totalPages = ref(0)
const pdfDoc = ref(null)

// EPUB相关
const epubContainer = ref(null)
const currentChapter = ref(1)
const totalChapters = ref(0)

// TXT相关
const textContent = ref('')

// 通用
const readerContainer = ref(null)

const goBack = () => {
  router.push('/library')
}

const downloadBook = async () => {
  if (!book.value) return
  
  try {
    const response = await fetch(`/api/books/download/${book.value.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = book.value.fileName || 'book'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    
  } catch (err) {
    console.error('下载失败:', err)
    alert('下载失败: ' + err.message)
  }
}

const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    readerContainer.value.requestFullscreen()
  }
}

const loadBook = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const result = await bookStore.getBook(route.params.id)
    if (result.success) {
      book.value = result.data
      await initializeReader()
    } else {
      error.value = result.message
    }
  } catch (err) {
    error.value = '加载书籍失败'
  } finally {
    loading.value = false
  }
}

const initializeReader = async () => {
  if (!book.value) return
  
  try {
    if (book.value.fileType === 'PDF') {
      await initializePDFReader()
    } else if (book.value.fileType === 'EPUB') {
      await initializeEPUBReader()
    } else if (book.value.fileType === 'TXT') {
      await initializeTXTReader()
    }
  } catch (err) {
    error.value = '初始化阅读器失败'
  }
}

const initializePDFReader = async () => {
  // 这里需要实现PDF.js的集成
  // 由于PDF.js较为复杂，这里提供一个基础的实现框架
  console.log('初始化PDF阅读器...')
  
  try {
    // 加载PDF文件
    const response = await fetch(`/api/books/download/${book.value.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const arrayBuffer = await response.arrayBuffer()
    console.log('PDF文件加载成功，大小:', arrayBuffer.byteLength)
    
    // 暂时设置模拟数据
    totalPages.value = 1
    currentPage.value = 1
    
    // 在canvas上显示PDF加载成功的提示
    const canvas = pdfCanvas.value
    if (canvas) {
      const ctx = canvas.getContext('2d')
      canvas.width = 600
      canvas.height = 800
      
      ctx.fillStyle = '#f8f8f8'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      
      ctx.fillStyle = '#333'
      ctx.font = '16px Arial'
      ctx.textAlign = 'center'
      ctx.fillText('PDF 阅读器', canvas.width / 2, 100)
      ctx.fillText('文件已加载，大小: ' + Math.round(arrayBuffer.byteLength / 1024) + ' KB', canvas.width / 2, 130)
      ctx.fillText('点击下载按钮查看完整内容', canvas.width / 2, 160)
      
      // 添加下载按钮的提示
      ctx.fillStyle = '#666'
      ctx.font = '14px Arial'
      ctx.fillText('注：完整的PDF阅读器需要集成PDF.js库', canvas.width / 2, 200)
    }
    
  } catch (err) {
    console.error('PDF初始化失败:', err)
    error.value = '加载PDF失败: ' + err.message
  }
}

const initializeEPUBReader = async () => {
  // 这里需要实现EPUB.js的集成
  console.log('初始化EPUB阅读器...')
  
  try {
    // 加载EPUB文件
    const response = await fetch(`/api/books/download/${book.value.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const arrayBuffer = await response.arrayBuffer()
    console.log('EPUB文件加载成功，大小:', arrayBuffer.byteLength)
    
    // 暂时设置模拟数据
    totalChapters.value = 1
    currentChapter.value = 1
    
    // 在容器中显示EPUB加载成功的提示
    const container = epubContainer.value
    if (container) {
      container.innerHTML = `
        <div style="padding: 40px; text-align: center; font-family: Arial, sans-serif;">
          <h2 style="color: #333; margin-bottom: 20px;">EPUB 阅读器</h2>
          <p style="color: #666; margin-bottom: 10px;">文件已加载，大小: ${Math.round(arrayBuffer.byteLength / 1024)} KB</p>
          <p style="color: #666; margin-bottom: 20px;">点击下载按钮查看完整内容</p>
          <div style="background: #f8f8f8; padding: 20px; border-radius: 8px; margin: 20px 0;">
            <p style="color: #999; font-size: 14px;">注：完整的EPUB阅读器需要集成EPUB.js库</p>
            <p style="color: #999; font-size: 14px;">当前为演示版本</p>
          </div>
        </div>
      `
    }
    
  } catch (err) {
    console.error('EPUB初始化失败:', err)
    error.value = '加载EPUB失败: ' + err.message
  }
}

const initializeTXTReader = async () => {
  // 加载TXT文件内容
  try {
    console.log('开始加载TXT文件，书籍ID:', book.value.id)
    const response = await fetch(`/api/books/download/${book.value.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const text = await response.text()
    textContent.value = text
    console.log('TXT文件加载成功，内容长度:', text.length)
  } catch (err) {
    console.error('TXT文件加载失败:', err)
    error.value = '加载文本内容失败: ' + err.message
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    renderPDFPage()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    renderPDFPage()
  }
}

const prevChapter = () => {
  if (currentChapter.value > 1) {
    currentChapter.value--
    renderEPUBChapter()
  }
}

const nextChapter = () => {
  if (currentChapter.value < totalChapters.value) {
    currentChapter.value++
    renderEPUBChapter()
  }
}

const renderPDFPage = () => {
  // 实现PDF页面渲染
  console.log('渲染PDF页面:', currentPage.value)
}

const renderEPUBChapter = () => {
  // 实现EPUB章节渲染
  console.log('渲染EPUB章节:', currentChapter.value)
}

onMounted(() => {
  loadBook()
})

onUnmounted(() => {
  // 清理资源
  if (pdfDoc.value) {
    pdfDoc.value.destroy()
  }
})
</script>

<style scoped>
.reader-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.reader-header {
  background: var(--background-color);
  border-bottom: 1px solid var(--border-color);
  padding: 15px 0;
  flex-shrink: 0;
}

.reader-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.book-info {
  text-align: center;
  flex: 1;
}

.book-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 5px;
}

.book-author {
  font-size: 14px;
  color: var(--text-secondary);
}

.reader-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.loading, .error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-secondary);
}

.reader-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.reader-notice {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 15px;
  margin: 15px;
  text-align: center;
  color: #6c757d;
  font-size: 14px;
}

.reader-notice p {
  margin: 5px 0;
}

.reader-notice p:first-child {
  font-weight: 500;
  color: #495057;
}

.pdf-reader, .epub-reader, .txt-reader {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.pdf-canvas {
  flex: 1;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.epub-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.txt-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: var(--surface-color);
}

.txt-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: Georgia, serif;
  font-size: 16px;
  line-height: 1.8;
  color: var(--text-primary);
}

.pdf-controls, .epub-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 15px;
  background: var(--surface-color);
  border-top: 1px solid var(--border-color);
}

.page-info, .chapter-info {
  font-size: 14px;
  color: var(--text-secondary);
  min-width: 80px;
  text-align: center;
}

.unsupported {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-secondary);
}

@media (max-width: 768px) {
  .reader-controls {
    padding: 0 15px;
  }
  
  .book-title {
    font-size: 16px;
  }
  
  .pdf-controls, .epub-controls {
    gap: 10px;
    padding: 10px;
  }
  
  .txt-content {
    padding: 15px;
  }
  
  .txt-content pre {
    font-size: 14px;
  }
}
</style>